<?php
/**
 * Created by PhpStorm.
 * Author: 黑瞎子
 * Date: 2018/3/17
 * Time: 19:24
 */

namespace app\api\controller\v1;


use app\api\service\UserToken;
use app\api\validate\AppTokenGet;
use app\api\validate\TokenGet;
use app\api\model\User as UserModel;
use app\lib\exception\ParameterException;
use app\api\service\Token as TokenService;
use app\api\service\AppToken as AppTokenService;
use app\lib\exception\TokenException;
use think\Cache;
use think\Request;

class Token
{
    /*
     * 通过code获取Token令牌
     * @url /token/user
     * @type POST
     * @code 小程序传递的用户code码
     * */
    public function getToken($code = ''){
        (new TokenGet())->goCheck();
        $ut = new UserToken($code);
        $token = $ut->get();
        return [
            'token' => $token
        ];
    }

    public function getUser(){
        $user = UserModel::getOpenID('ohhED0dGLjceozS7JgqguUTX_2hI');
        return $user;
    }

    /*
     * 验证Token
     * @type post
     * */
    public function verifyToken($token = ''){
        if(!$token){
            throw new ParameterException([
                'msg' => 'token不允许为空'
            ]);
        }
        $valid = TokenService::verifyToken($token);
        return [
            'isvalid' =>$valid
        ];
    }

    /*
     * 第三方应用获取token令牌
     * @url /app_token?
     * @POST $ac=:ac $sc=:secret
     * 返回token
     * */
    public function getAppToken($ac = '', $se = ''){
        (new AppTokenGet())->goCheck();
        $app = new AppTokenService();
        $token = $app->get($ac, $se);
        return [
            'token' => $token
        ];
    }

    /*
     * 第三方登录 根据token获取用户权限 role
     * @url /role
     * @POST $token = token
     * 返回用户权限 role: scope
     * */
    public function getroleByToken($token){
        if (!$token){
            throw new ParameterException([
                'msg' => 'token不能为空'
            ]);
        }
        $exist = Cache::get($token);
        if (!$exist){
            throw new TokenException();
        }
        if (array_key_exists('scope',$exist) && $exist['scope'] ==32 ){
            $role = 'admin';
            return [
                'roles' => $role
            ];
        }else{
            throw new ParameterException([
                'msg' => '权限不够'
            ]);
        }
    }

}